﻿using System.Text;

namespace 并发测试
{
    internal class Program
    {
        private static ReaderWriterLockSlim lockSlim = new ReaderWriterLockSlim();
        static void Main(string[] args)
        {
            //Parallel.Invoke(WriteTxt1, WriteTxt2);
            //Console.WriteLine("****数据修改完成****");

            Parallel.Invoke(WriteTxt1, WriteTxt2);
            Console.WriteLine("****数据查询完成****");
            Console.ReadKey();
        }
        public static void WriteTxt1()
        {
            lockSlim.EnterWriteLock();
            try
            {
                File.WriteAllText("test.txt", "hello 111");
            }
            finally
            {
                lockSlim.ExitWriteLock();
            }
        }

        public static void WriteTxt2()
        {
            lockSlim.EnterWriteLock();
            try
            {
                File.WriteAllText("test.txt", "hello 222");
            }
            finally
            {
                lockSlim.ExitWriteLock();
            }
        }

        public static void ReadTxt1()
        {
            Thread.Sleep(3000);
            lockSlim.EnterReadLock();
            try
            {
                var fileInfo = File.ReadAllText("test.txt");
                Console.WriteLine($"ReadTxt1读取内容：{fileInfo}");
            }
            finally
            {
                lockSlim.ExitReadLock();
            }
        }

        public static void ReadTxt2()
        {
            lockSlim.EnterReadLock();
            try
            {
                var fileInfo = File.ReadAllText("test.txt");
                Console.WriteLine($"ReadTxt2读取内容：{fileInfo}");
            }
            finally
            {
                lockSlim.ExitReadLock();
            }
        }
    }
}
